package com.gxc.recursion;

/**
 * 用螺旋的方式打印矩阵，比如如下的矩阵
 * 0 1 2 3
 * 4 5 6 7
 * 8 9 10 11
 * 打印顺序为:01237111098456
 */
public class Spiral {

    public static void main(String[] args) {
        int[][] array = generate();
        System.out.println("-----------");
        print(array, 0, 0, array.length-1, array[0].length-1);
    }

    public static void print(int[][] array, int upleftX, int upleftY, int lowRightX, int lowRightY) {
        if (upleftX > lowRightX || upleftY>lowRightY) return;
        //只有一行
        if (upleftX ==lowRightX) {
            for (int i = upleftY; i <= lowRightY; i++) {
                System.out.print(array[upleftX][i]);
            }
            //只有一列
        } else if (upleftY == lowRightY) {
            for (int i = upleftX; i <= lowRightX; i++) {
                System.out.print(array[i][lowRightY]);
            }
        } else {
            for (int i = upleftY; i <= lowRightY; i++) {
                System.out.print(array[upleftX][i]);
            }
            for (int i = upleftX+1; i <= lowRightX; i++) {
                System.out.print(array[i][lowRightY]);
            }
            for (int i = lowRightY-1; i >= upleftY; i--) {
                System.out.print(array[lowRightX][i]);
            }
            for (int i = lowRightX-1; i > upleftX; i--) {
                System.out.print(array[i][upleftY]);
            }
        }

        print(array, upleftX+1, upleftY+1, lowRightX-1, lowRightY-1);
    }

    private static int[][] generate() {
        int[][] a = new int[3][4];

        int start = 0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                a[i][j] = start;
                start++;
            }
        }

        return a;
    }
}
